package com.lalosoft.misgastos.activities;

import java.io.IOException;
import java.sql.SQLException;

import org.json.JSONException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lalosoft.misgastos.R;
import com.lalosoft.misgastos.config.GastosManager;
import com.lalosoft.misgastos.domain.Account;
import com.lalosoft.misgastos.service.GastosTarjetaService;
import com.lalosoft.misgastos.service.impl.GastosTarjetaServiceImpl;

public class SettingsActivity extends Activity {
	
	private EditText username;
	private EditText password;
	private EditText email;
	private Button applyButton;
	private Account account = null;
	private String result;
	private Context context = SettingsActivity.this;
	
	private static String TAG = "SettingsActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		username = (EditText) findViewById(R.id.settings_username);
		password = (EditText) findViewById(R.id.settings_password);
		email = (EditText) findViewById(R.id.settings_email);
		applyButton = (Button) findViewById(R.id.settings_button_apply);
		checkLogged();
		applyButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
					if(GastosManager.getInstance(getApplicationContext()).isLogged()){
						updateUser();
					} else {
						saveUser();
					}
			}
		});
	}
	
	private void fillData(){
		this.email.setText("gonzalomartin2002@hotmail.com");
		this.password.setText("1234");
		this.username.setText("user");
	}
	
	private void updateUser(){
		account = GastosManager.getInstance(getApplicationContext()).getCurrentAccount();
		account.setUsername(username.getText().toString());
		account.setEmail(email.getText().toString());
		account.setPassword(password.getText().toString());
		final ProgressDialog dialog;
		dialog = new ProgressDialog(context);
		dialog.setMessage("Espere...");
		dialog.show();
		final Handler h = new Handler();
		Thread t = new Thread(){
			@Override
			public void run() {
				GastosTarjetaService service = new GastosTarjetaServiceImpl();
				try {
					result = service.updateAccount(account, GastosManager.getInstance(getApplicationContext()).getCurrentAccount().getUserToken());
				} catch (IOException e) {
					Log.e(TAG, "Error en actualizar usuario en la web: " + e.getMessage(), e);
				} catch (JSONException e) {
					Log.e(TAG, "Error en JSON: " + e.getMessage(), e);
				}
				h.post(new Runnable() {
					
					@Override
					public void run() {
						dialog.dismiss();
						if(result.equals("ok")){
							try {
								GastosManager.getInstance(getApplicationContext()).updateAccount(account);
								Log.i(TAG, "Se ha actualizado el usuario");
								Toast.makeText(context, "Se ha actualizado el usuario", Toast.LENGTH_SHORT).show();
								Intent i = new Intent(context, MainActivity.class);
								startActivity(i);
								finish();
							} catch (SQLException e) {
								Log.e(TAG, "Error en actualizar usuario en DB: " + e.getMessage(), e);
								Toast.makeText(context, "Usuario no actualizado", Toast.LENGTH_SHORT).show();
							}
						} else {
							if(result.equals("user exist")){
								Log.e(TAG, "Error en actualizar usuario en web ");
								Toast.makeText(context, "Usuario existente!", Toast.LENGTH_SHORT).show();
							} else {
								Log.e(TAG, "Error en actualizar usuario en web ");
								Toast.makeText(context, "Usuario no actualizado", Toast.LENGTH_SHORT).show();
							}
						}
					}
				});
			}
		};
		t.start();
	}
	
	private void saveUser(){
		account = new Account();
		account.setPassword(password.getText().toString());
		account.setEmail(email.getText().toString());
		account.setUsername(username.getText().toString());
		final ProgressDialog dialog;
		dialog = new ProgressDialog(context);
		dialog.setMessage("Espere...");
		dialog.show();
		final Handler h = new Handler();
		Thread t = new Thread(){
			@Override
			public void run() {
				GastosTarjetaService service = new GastosTarjetaServiceImpl();
				try {
					result = service.saveAccount(account);
				} catch (IOException e) {
					Log.e(TAG, "Error en crear usuario en la web: " + e.getMessage(), e);
				} catch (JSONException e) {
					Log.e(TAG, "Error en JSON: " + e.getMessage(), e);
				}
				h.post(new Runnable() {
					
					@Override
					public void run() {
						dialog.dismiss();
						if(!result.equals("")){
							if(result.equals("user exist")){
								Toast.makeText(context, "Usuario existente", Toast.LENGTH_SHORT).show();
								Log.d(TAG, "Usuario existente");
							} else {
								try {
									account.setUserToken(result);
									GastosManager.getInstance(context).setUser(account);
									Toast.makeText(context, "Datos guardados!", Toast.LENGTH_SHORT).show();
									Log.i(TAG, "Se ha creado un usuario");
									GastosManager.getInstance(context).logged();
									Intent i = new Intent(context, MainActivity.class);
									startActivity(i);
									finish();
								} catch (SQLException e) {
									Log.e(TAG, "Error en guardar usuario en DB: " + e.getMessage(), e);
									Toast.makeText(context, "Usuario no guardado", Toast.LENGTH_SHORT).show();
								}
							}
						}
						clearFields();
					}
				});
			}
		};
		t.start();
	}
	
    private void checkLogged() {
		if(GastosManager.getInstance(getApplicationContext()).isLogged()){
			Account account = GastosManager.getInstance(getApplicationContext()).getCurrentAccount();
			this.username.setText(account.getUsername());
			this.email.setText(account.getEmail());
			this.password.setText(account.getPassword());
			applyButton.setText("Actualizar");
		} else {
			fillData();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	if(GastosManager.getInstance(getApplicationContext()).isLogged()){
	    		Intent i = new Intent(SettingsActivity.this, MainActivity.class);
				startActivity(i);	
	    	}
			finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	private void clearFields(){
		this.email.setText("");
		this.username.setText("");
		this.password.setText("");
	}
}
